from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from login.middlewares import getEmail
from register.models import Player
from gobang.consumers import battlers
# from gobang.consumers import battlers

# Create your views here.
def hall(request):
    email=getEmail(request)
    if email==None:
        return HttpResponseRedirect('/login/')
    headShot=Player.objects.filter(email=email)[0].headShot.url
    return render(request,'hall.html',{'title':'hall','headShot':headShot})

def list(request):
    email=getEmail(request)
    if email==None:
        return HttpResponseRedirect('/login/')
    headShot=Player.objects.filter(email=email)[0].headShot.url
    dataList=[]
    for key in battlers.keys():
        print('list',key)
        dataList.append([key,len(battlers[key])])
    return render(request,'list.html',{'title':'list','list':dataList,'headShot':headShot})

def aboutme(request):
    email=getEmail(request)
    if email==None:
        return HttpResponseRedirect('/login/')
    if request.method=='POST':
        Player.objects.filter(email=email).update(nickname=request.POST.get('nickname'))
    else:
        player=Player.objects.filter(email=email)[0]
        return render(request,'aboutme.html',
        {
            'title':'aboutme',
            'headShot':player.headShot.url,
            'nickname':player.nickname,
            'email':player.email,
            })

def create(request):
    email=getEmail(request)
    if email==None:
        return HttpResponseRedirect('/login/')
    method=request.method
    if method=='POST':
        roomID=request.POST.get('roomID')
        if roomID in battlers.keys():
            return HttpResponse({'error':'ID已经存在'})
        else:
            return HttpResponseRedirect('/gobang/battle/'+roomID+'/')
    headShot=Player.objects.filter(email=email)[0].headShot.url
    return render(request,'create.html',{'title':'create','headShot':headShot})
